package com.halflife.comeElectricity.orderMng.unPay;

import com.halflife.comeElectricity.orderMng.cancel.CancelOrderController;
import com.halflife.comeElectricity.orderMng.order.*;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Calendar;

@RestController
@RequestMapping("mc_unPayOrder")
public class UnPayOrderController {

    private Logger log = LoggerFactory.getLogger(CancelOrderController.class);

    @Resource
    private UnPayOrderRepository unPayOrderRepository;
    @Resource
    private UnPayOrderExtRepository unPayOrderExtRepository;
    @Resource
    private OrderRepository orderRepository;
    @Resource
    private OrderExtRepository orderExtRepository;

    /**
     * 生成取消訂單 並刪除訂單 add by liuj3
     * @param orderId
     */

    public void generatorUnpayLog(Integer orderId){
        try {
            BeanUtilsBean beanUtilsBean = new BeanUtilsBean();
            beanUtilsBean.getConvertUtils().register(new org.apache.commons.beanutils.converters.BigDecimalConverter(null), BigDecimal.class);
            //查詢訂單以及訂單詳情
            if(orderId!=null) {
                //获取订单
                Order order = orderRepository.selectByPrimaryKey(orderId);
                order.setStatus(OrderEnum.CANCEL.m_orderStatus.byteValue());
                //复制Order对象
                UnPayOrder unPayOrder = new UnPayOrder();
                beanUtilsBean.copyProperties(unPayOrder, order);
                unPayOrder.setId(null);
                unPayOrder.setCancelDate(Calendar.getInstance().getTimeInMillis());
                //创建取消订单
                Integer unPayOrderRepositroyId = unPayOrderRepository.insert(unPayOrder);
                //获取订单详情
                OrderExt orderExt = orderExtRepository.selectByPrimaryKey(orderId);
                //复制订单详情
                UnPayOrderExt unPayOrderExt = new UnPayOrderExt();
                unPayOrderExt.setEndTime(Calendar.getInstance().getTimeInMillis());
                beanUtilsBean.copyProperties(unPayOrderExt, orderExt);
                //指定订单详情id对应CancelOrder
                unPayOrderExt.setId(unPayOrder.getId());
                //创建取消订单详情
                unPayOrderExtRepository.insert(unPayOrderExt);
                //删除订单以及订单详情
                orderRepository.deleteByPrimaryKey(orderId);
                orderExtRepository.deleteByPrimaryKey(orderId);
            }
        } catch (Exception e) {
            log.error("================订单取消错误===================");
            log.error(e.getMessage(), e);
        }
    }
}
